package co.fitstart.admin.handler.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.http.Consts;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.SignatureUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.admin.handler.PaymentHandler;
import co.fitstart.entity.order.Order;

/**
 * 
 * @author mohanlan
 *
 */
@Component("paymentHandler")
public class PaymentHandlerImpl implements PaymentHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(PaymentHandlerImpl.class);
    
    @Value("#{ctx['api.host']}")
    private String APIHOST;
    
    @Resource(name = "payment")
    private Properties properties;
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.handler.PaymentHandler#payWechat(java.lang.String, java.lang.Long, int, java.lang.String)
     */
    public Result payOrder(String orderNo, Long customerId, int amount, String requestNo, String channel) {
        
        Result result = new Result();
        
        try {
            
            String appId = properties.getProperty("appid");
            String appsecret = properties.getProperty("appsecret");
            
            Map<String, String> parameters = new LinkedHashMap<String, String>();
            parameters.put("appid", appId);
            parameters.put("channel", channel);
            parameters.put("order_no", orderNo);
            parameters.put("customer_id", customerId.toString());
            parameters.put("amount", String.valueOf(amount));
            parameters.put("pay_time", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
            parameters.put("request_no", requestNo);
            
            String queryString = StringUtils.toSortedQueryString(parameters) + "&key=" + appsecret;
            String signature = SignatureUtils.makeMD5Signature(queryString).toUpperCase();
            
            parameters.put("signature", signature);
            String content = JsonUtils.toJsonString(parameters);
            
            Response response = Request.Post(APIHOST + "/v1/payments/callback")
                                       .bodyString(content, ContentType.APPLICATION_JSON)
                                       .connectTimeout(100000)
                                       .socketTimeout(100000)
                                       .execute();
            
            String body = response.returnContent().asString(Consts.UTF_8);
            logger.trace("PaymentHandlerImpl#prePay() - Get response body [{}].", body);
            
            result = JSON.parseObject(body, Result.class);
            
        } catch (Exception e) {
            logger.error("PaymentHandlerImpl#prePay() - Requesting wechat pay order api euncouters IO exception: [{}]", e);
        }
        
        return result;
        
        
        
        
        
//        Result result = new Result();
//        
//        try {
//            
//            Map<String, String> parameters = new LinkedHashMap<String, String>();
//            parameters.put("channel", wechatChannel);
//            parameters.put("orderNo", orderNo);
//            parameters.put("amount", String.valueOf(amount));
//            parameters.put("paymentTime", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
//            parameters.put("transactionCode", requestNo);
//            
//            String content = JsonUtils.toJsonString(parameters);
//            
//            Response response = Request.Post(APIHOST + "/v1/payments/callback")
//                                       .bodyString(content, ContentType.APPLICATION_JSON)
//                                       .connectTimeout(100000)
//                                       .socketTimeout(100000)
//                                       .execute();
//            
//            String body = response.returnContent().asString(Consts.UTF_8);
//            logger.trace("PaymentHandlerImpl#prePay() - Get response body [{}].", body);
//            
//            result = JSON.parseObject(body, Result.class);
//            
//        } catch (Exception e) {
//            logger.error("PaymentHandlerImpl#prePay() - Requesting wechat pay order api euncouters IO exception: [{}]", e);
//        }
//        
//        return result;

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
//        Result result = new Result();
//        
//        // Get order number, customer id and notify url
//        String appid = properties.getProperty("appid");
//        String appsecret = properties.getProperty("appsecret");
//        String payTimeString = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
//        
//        Map<String, String> parameters = new HashMap<String, String>();
//        parameters.put("appid", appid);
//        parameters.put("channel", wechatChannel);
//        parameters.put("order_no", orderNo);
//        parameters.put("customer_id", customerId.toString());
//        parameters.put("amount", String.valueOf(amount));
//        parameters.put("pay_time", payTimeString);
//        parameters.put("request_no", requestNo);
//        
//        String queryString = StringUtils.toSortedQueryString(parameters) + "&key=" + appsecret;
//        String signature = SignatureUtils.makeMD5Signature(queryString).toUpperCase();
//        
//        try {
//            
//            Response response = Request.Post(APIHOST + "/v1/payments/callback")
//                                       .connectTimeout(10000)
//                                       .socketTimeout(10000)
//                                       .bodyForm(
//                                           Form.form()
//                                               .add("appid", appid)
//                                               .add("channel", wechatChannel)
//                                               .add("order_no", orderNo)
//                                               .add("customer_id", customerId.toString())
//                                               .add("amount", String.valueOf(amount))
//                                               .add("pay_time", payTimeString)
//                                               .add("request_no", requestNo)
//                                               .add("signature", signature)
//                                               .build(),
//                                           Consts.UTF_8
//                                       ).execute();
//            
//            String body = response.returnContent().asString(Consts.UTF_8);
//            result = JSON.parseObject(body, Result.class);
//            
//        } catch (IOException e) {
//            logger.error("OrderHandlerImpl#synchronizeOrderStat() - Synchronizing order status occurs IO exception.");
//            e.printStackTrace();
//        }
//        
//        return result;
        
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.admin.handler.PaymentHandler#payOrder(co.fitstart.entity.order.Order, java.lang.String, java.lang.Long, int, java.lang.String, java.lang.String, java.lang.String, java.math.BigDecimal)
     */
    public Result payOrder(Order order, String orderNo, Long customerId, int amount, String requestNo, String channel,
            String orderNumber) {
        Result result = new Result();
        
        try {
            
            String appId = properties.getProperty("appid");
            String appsecret = properties.getProperty("appsecret");
            
            Map<String, String> parameters = new LinkedHashMap<String, String>();
            parameters.put("appid", appId);
            parameters.put("channel", channel);
            parameters.put("order_no", orderNo);
            parameters.put("customer_id", customerId.toString());
            parameters.put("amount", String.valueOf(amount));
            parameters.put("pay_time", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
            parameters.put("request_no", requestNo);
            
            String queryString = StringUtils.toSortedQueryString(parameters) + "&key=" + appsecret;
            String signature = SignatureUtils.makeMD5Signature(queryString).toUpperCase();
            
            parameters.put("signature", signature);
            parameters.put("order_number", orderNumber);
            String content = JsonUtils.toJsonString(parameters);
            
            Response response = Request.Post(APIHOST + "/v1/payments/callback")
                                       .bodyString(content, ContentType.APPLICATION_JSON)
                                       .connectTimeout(100000)
                                       .socketTimeout(100000)
                                       .execute();
            
            String body = response.returnContent().asString(Consts.UTF_8);
            logger.trace("PaymentHandlerImpl#prePay() - Get response body [{}].", body);
            
            result = JSON.parseObject(body, Result.class);
            
        } catch (Exception e) {
            logger.error("PaymentHandlerImpl#prePay() - Requesting wechat pay order api euncouters IO exception: [{}]", e);
        }
        
        return result;
    }
    
}
